package cn.zhxu.toys.tree;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TreeUtils {

    public static <T extends TreeAble, R extends TreeOutput<R>> List<R> buildTree(List<T> inputs, Function<T, R> convertor) {
        Stream<T> roots = inputs.stream().filter(i -> i.getParentId() == null || i.getParentId() == 0);
        return doBuildTree(roots, inputs, convertor);
    }

    public static <T extends TreeAble, R extends TreeOutput<R>> List<R> doBuildTree(Stream<T> roots, List<T> inputs, Function<T, R> convertor) {
        return roots.map(input -> {
                    Stream<T> list = inputs.stream().filter(i -> Objects.equals(i.getParentId(), input.getId()));
                    R result = convertor.apply(input);
                    List<R> children = doBuildTree(list, inputs, convertor);
                    result.setChildren(children);
                    return result;
                })
                .collect(Collectors.toList());
    }

}
